<template>
  <div class="page-config">
    <a-form :model="formData" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-form-item label="表单类型" required>
        <a-select v-model:value="formData.type" style="width: 100%">
          <a-select-option value="form">表单</a-select-option>
          <a-select-option value="page">页面</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="表单ID" required>
        <a-input v-model:value="formData.id" />
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
import { computed, onMounted, ref, watch } from 'vue'
import { useBpmnModeler, useBpmnSelectedElem } from '/@/config/app.hooks'

export default {
  name: 'PageConfig',
  setup() {
    const bpmnModeler = useBpmnModeler()
    const bpmnSelectedElem = useBpmnSelectedElem()

    const formData = ref({
      type: 'form',
      id: ''
    })

    const updateFormData = () => {
      const selectedElem = bpmnSelectedElem.value
      if (!selectedElem) {
        return
      }
      const bo = selectedElem.businessObject
      const extensionElements = bo.get('extensionElements')
      if (extensionElements) {
        const values = extensionElements.values
        const formConfig = values.find(v => v.$type === 'smart:FormConfig')
        if (formConfig) {
          formData.value = {
            type: formConfig.type || 'form',
            id: formConfig.id || ''
          }
        }
      }
    }

    watch(() => bpmnSelectedElem.value, () => {
      updateFormData()
    }, { immediate: true })

    watch(() => formData.value, (val) => {
      const selectedElem = bpmnSelectedElem.value
      if (!selectedElem) {
        return
      }
      const modeling = bpmnModeler.value.get('modeling')
      const bo = selectedElem.businessObject
      const extensionElements = bo.get('extensionElements') || bpmnModeler.value.get('moddle').create('bpmn:ExtensionElements')
      const formConfig = bpmnModeler.value.get('moddle').create('smart:FormConfig', {
        type: val.type,
        id: val.id
      })
      extensionElements.values = [formConfig]
      modeling.updateProperties(selectedElem, {
        extensionElements
      })
    }, { deep: true })

    return {
      formData
    }
  }
}
</script>

<style scoped>
.page-config {
  padding: 12px;
}
</style>
